package com.jack.leetcode.eachproblem_2020;

public class 两数相加 {

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode tmp = result;
        boolean isAdd = false;
        while(l1 != null && l2 != null){
            int curValue = l1.val + l2.val + (isAdd ? 1 : 0);
            result.next = new ListNode( curValue % 10);
            result = result.next;
            isAdd = curValue > 9;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1 != null){
            int curValue = l1.val + (isAdd ? 1 : 0);
            result.next = new ListNode(curValue % 10);
            result = result.next;
            l1 = l1.next;
            isAdd = curValue > 9;
        }
        while(l2 != null){
            int curValue = l2.val + (isAdd ? 1 : 0);
            result.next = new ListNode(curValue % 10);
            result = result.next;
            l2 = l2.next;
            isAdd = curValue > 9;
        }
        if(isAdd){
            result.next = new ListNode(1);
        }
        return tmp.next;
    }
}
